package com.example.demo;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Service
public class UserService {

    private List<User> userList = new ArrayList<>();
    private Integer nextId = 1;

    public UserService() {
        userList.add(new User(nextId++, "Alice"));
        userList.add(new User(nextId++, "Bob"));
    }

    public List<User> listUsers() {
        return userList;
    }

    public User getUserById(Integer id) {
        for (User user : userList) {
            if (user.getId().equals(id)) {
                return user;
            }
        }
        return null;
    }

    public User createUser(User user) {
        user.setId(nextId++);
        userList.add(user);
        return user;
    }

    public User updateUser(Integer id, User updatedUser) {
        for (User user : userList) {
            if (user.getId().equals(id)) {
                user.setName(updatedUser.getName());
                return user;
            }
        }
        return null;
    }

    public boolean deleteUser(Integer id) {
        Iterator<User> iterator = userList.iterator();
        while (iterator.hasNext()) {
            User user = iterator.next();
            if (user.getId().equals(id)) {
                iterator.remove();
                return true;
            }
        }
        return false;
    }
}